const ApiError = require('../error/api_error');
const ApiErrorNames = require('../error/api_error_name');
const ApiErrorMap = require('../error/api_error_map');

//只对api前缘路由执行
const responseFormatter = (apiPrefix) => async (ctx, next) => {

  if (ctx.request.path.startsWith(apiPrefix) && (ctx.request.path !=='/api/pings')) {

    //是api访问
    try {
      // 先去执行路由
      await next();
      if(ctx.response.status === 250) throw new ApiError(ApiErrorNames.USER_ERROR);
      if (ctx.response.status === 200) {

        ctx.body = {
          code: 'success',
          message: '成功!',
          result: ctx.body,
        };
      }

    } catch (error) {

      // 如果异常类型是API异常，将接收的错误信息添加到响应体中返回。
      if (error instanceof ApiError) {
        ctx.response.body = {
          code: error.code,
          message: error.message,
          result: error,

        };

      } else {//不是APIERROR的话重新封装一下
        ctx.status = 400;
        ctx.response.body = {
          code: error.name,
          message: error.message,
          result: error,
        };
      }
    }
  } else {

    //不是api开头的放行
    await next();
  }
};

module.exports = responseFormatter;
